package com.qx.cn.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.cn.model.Role;
import com.qx.cn.model.RoleGroup;
import com.qx.cn.model.RoleGroupMapping;
import com.qx.cn.model.UserRoleGroup;
import com.qx.cn.service.RoleGroupMappingService;
import com.qx.cn.service.RoleGroupService;
import com.qx.cn.service.RoleService;
import com.qx.cn.service.UserRoleGroupService;
import com.qx.cn.vo.RoleGroupVO;
import com.qx.cn.vo.RoleVO;

@ParentPackage("netxzt")
@Namespace("/")
@InterceptorRefs({@InterceptorRef("content")})
@Results({@Result(name = "outlogin", location = "/admin!loseSession"), @Result(name = "getOutlogin", location = "/admin!otherlogin"),
    @Result(name = "roleGroupList", location = "/WEB-INF/page/roleGroupInfo/roleGroupList.jsp")})
@Action(value = "rolegroup", interceptorRefs = {@InterceptorRef("loginedCheck")})
public class RoleGroupAction extends BaseAction
{
    /**
     * 注释内容
     */
    private static final long serialVersionUID = 3387757088038964500L;
    
    private int page;
    
    private int rows;
    
    private Long groupId;
    
    private String groupName;
    
    private Integer enabled;
    
    private String groupDesc;
    
    private String orgCode;
    
    private String strBuffer;
    
    private String userId;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private RoleGroupService roleGroupService;
    
    @Autowired
    private UserRoleGroupService userRoleGroupService;
    
    @Autowired
    private RoleGroupMappingService roleGroupMappingService;
    
    public String roleGroupListForm()
    {
        return "roleGroupList";
    }
    
    public String queryRoleListByPage()
    {
        List results = roleGroupService.queryRoleGroupsByPage(page, rows);
        JSONArray arrJson = new JSONArray();
        if (results.size() > 0)
        {
            for (int i = 0; i < results.size(); i++)
            {
                Object[] row = (Object[])results.get(i);
                JSONObject json = new JSONObject();
                json.put("groupId", (Integer)row[0]);
                json.put("groupName", (String)row[1]);
                json.put("enabled", (Integer)row[2]);
                json.put("groupDesc", (String)row[3]);
                String optUrl = "<span style='color:#00C;cursor:hand;' onclick=giveRoleToGroup('" + (Integer)row[0] + "')>[设置角色]</span>&nbsp;";
                String optUser = "<span style='color:#00C;cursor:hand;' onclick=giveUserToGroup('" + (Integer)row[0] + "','【" + (String)row[1] + "】')>[设置用户]</span>";
                json.put("optStr", optUrl + optUser);
                arrJson.add(json);
            }
        }
        
        JSONObject object = new JSONObject();
        object.put("total", Integer.valueOf(results.size()));
        object.put("rows", arrJson);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveRoleGroup()
        throws IOException
    {
        if (groupId != null)
        {
            RoleGroup reRoleGroup = roleGroupService.loadRoleGroupById(groupId);
            reRoleGroup.setGroupName(groupName);
            reRoleGroup.setEnabled(enabled);
            reRoleGroup.setGroupDesc(groupDesc);
            roleGroupService.saveRoleGroup(reRoleGroup);
        }
        else
        {
            RoleGroup roleGroup = new RoleGroup();
            roleGroup.setGroupName(groupName);
            roleGroup.setEnabled(enabled);
            roleGroup.setGroupDesc(groupDesc);
            roleGroupService.saveRoleGroup(roleGroup);
        }
        
        JSONObject object = new JSONObject();
        object.put("result", 1);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String deleteRoleGroup()
    {
        boolean flag = roleGroupService.deleteRoleGroup(groupId);
        boolean flag1 = roleGroupMappingService.deleteGroupRoles(groupId);
        boolean flag2 = userRoleGroupService.deleteGroupsUserByGroupId(groupId);
        JSONObject object = new JSONObject();
        if ((flag) && (flag1) && (flag2))
        {
            object.put("result", 1);
            object.put("errorMsg", "删除角色组成功");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "删除角色组失败");
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String loadRoleGroupById()
    {
        RoleGroup roleGroup = roleGroupService.loadRoleGroupById(groupId);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(roleGroup));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String queryAllRolesToGroup()
    {
        List<Role> roles = roleService.queryAllRoles();
        List<RoleGroupMapping> roleGroMaps = roleGroupMappingService.queryGroupRolesById(groupId);
        List<RoleVO> roleVOs = new ArrayList<RoleVO>();
        for (Role role : roles)
        {
            int sign = 0;
            RoleVO roleVO = new RoleVO();
            for (RoleGroupMapping rgm : roleGroMaps)
            {
                if (role.getRoleId().toString().equals(rgm.getRoleId()))
                {
                    sign = 1;
                }
            }
            roleVO.setRoleId(role.getRoleId());
            roleVO.setRoleName(role.getRoleName());
            roleVO.setRoleDesc(role.getRoleDesc());
            roleVO.setEnabled(role.getEnabled());
            roleVO.setSign(Integer.valueOf(sign));
            roleVOs.add(roleVO);
        }
        JSONObject object = new JSONObject();
        object.put("datas", roleVOs);
        object.put("result", 1);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveRoleToGroup()
    {
        boolean flag = true;
        JSONObject object = new JSONObject();
        String[] roleId = strBuffer.split(",");
        List<RoleGroupMapping> roleGroupMappings = roleGroupMappingService.queryGroupRolesById(groupId);
        if (roleGroupMappings.size() > 0)
        {
            boolean flag2 = roleGroupMappingService.deleteGroupRoles(groupId);
            if (flag2)
            {
                for (int i = 0; i < roleId.length; i++)
                {
                    RoleGroupMapping roleGroupMapping = new RoleGroupMapping();
                    roleGroupMapping.setRoleId(roleId[i]);
                    roleGroupMapping.setGroupId(groupId);
                    boolean flag1 = roleGroupMappingService.saveRoleGroup(roleGroupMapping);
                    if (!flag1)
                    {
                        flag = false;
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < roleId.length; i++)
            {
                RoleGroupMapping roleGroupMapping = new RoleGroupMapping();
                roleGroupMapping.setRoleId(roleId[i]);
                roleGroupMapping.setGroupId(groupId);
                boolean flag1 = roleGroupMappingService.saveRoleGroup(roleGroupMapping);
                if (!flag1)
                {
                    flag = false;
                }
            }
        }
        
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置角色组成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置角色组失败!");
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveUserToRoleGroup()
    {
        boolean flag = true;
        JSONObject object = new JSONObject();
        String[] userId = strBuffer.split(",");
        List<UserRoleGroup> userRoleGroups = userRoleGroupService.queryUsersToGroupByOrgCode(orgCode, groupId);
        if (userRoleGroups.size() > 0)
        {
            boolean flag2 = userRoleGroupService.deleteUserGroupRoles(orgCode, groupId);
            if (flag2)
            {
                for (int i = 0; i < userId.length; i++)
                {
                    UserRoleGroup userRoleGroup = new UserRoleGroup();
                    userRoleGroup.setGroupId(groupId);
                    userRoleGroup.setOrgCode(orgCode);
                    userRoleGroup.setUserId(Long.valueOf(userId[i]));
                    boolean flag1 = userRoleGroupService.saveUserRoleGroup(userRoleGroup);
                    if (!flag1)
                    {
                        flag = false;
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < userId.length; i++)
            {
                UserRoleGroup userRoleGroup = new UserRoleGroup();
                userRoleGroup.setGroupId(groupId);
                userRoleGroup.setOrgCode(orgCode);
                userRoleGroup.setUserId(Long.valueOf(userId[i]));
                boolean flag1 = userRoleGroupService.saveUserRoleGroup(userRoleGroup);
                if (!flag1)
                {
                    flag = false;
                }
            }
            
        }
        
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置角色组成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置角色组失败!");
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String queryAllGroupsToUser()
    {
        List<RoleGroup> groups = roleGroupService.queryAllRoleGroups();
        List<UserRoleGroup> userGroups = userRoleGroupService.queryGroupsByUserId(Long.valueOf(userId));
        List<RoleGroupVO> groupVOs = new ArrayList<RoleGroupVO>();
        for (RoleGroup group : groups)
        {
            int sign = 0;
            RoleGroupVO roleGroupVO = new RoleGroupVO();
            for (UserRoleGroup urg : userGroups)
            {
                if (urg.getGroupId().equals(group.getGroupId()))
                {
                    sign = 1;
                }
            }
            
            roleGroupVO.setGroupId(group.getGroupId());
            roleGroupVO.setGroupName(group.getGroupName());
            roleGroupVO.setGroupDesc(group.getGroupDesc());
            roleGroupVO.setEnabled(group.getEnabled());
            roleGroupVO.setSign(Integer.valueOf(sign));
            groupVOs.add(roleGroupVO);
        }
        JSONObject object = new JSONObject();
        object.put("datas", groupVOs);
        object.put("result", 1);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveGroupToUser()
    {
        boolean flag = true;
        JSONObject object = new JSONObject();
        String[] groupId = strBuffer.split(",");
        List<UserRoleGroup> userGroups = userRoleGroupService.queryGroupsByUserId(Long.valueOf(userId));
        if (userGroups.size() > 0)
        {
            if (userRoleGroupService.deleteGroupsUser(Long.valueOf(userId)))
            {
                for (int i = 0; i < groupId.length; i++)
                {
                    UserRoleGroup userGroup = new UserRoleGroup();
                    userGroup.setGroupId(Long.valueOf(groupId[i]));
                    userGroup.setUserId(Long.valueOf(userId));
                    userGroup.setOrgCode(orgCode);
                    boolean flag1 = userRoleGroupService.saveUserGroup(userGroup);
                    if (!flag1)
                    {
                        flag = false;
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < groupId.length; i++)
            {
                UserRoleGroup userGroup = new UserRoleGroup();
                userGroup.setGroupId(Long.valueOf(groupId[i]));
                userGroup.setUserId(Long.valueOf(userId));
                userGroup.setOrgCode(orgCode);
                boolean flag1 = userRoleGroupService.saveUserGroup(userGroup);
                if (!flag1)
                {
                    flag = false;
                }
            }
        }
        
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "设置用户-角色组成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "设置用户-角色组失败!");
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public int getPage()
    {
        return page;
    }
    
    public void setPage(int page)
    {
        this.page = page;
    }
    
    public int getRows()
    {
        return rows;
    }
    
    public void setRows(int rows)
    {
        this.rows = rows;
    }
    
    public String getGroupName()
    {
        return groupName;
    }
    
    public void setGroupName(String groupName)
    {
        this.groupName = groupName;
    }
    
    public Integer getEnabled()
    {
        return enabled;
    }
    
    public void setEnabled(Integer enabled)
    {
        this.enabled = enabled;
    }
    
    public String getGroupDesc()
    {
        return groupDesc;
    }
    
    public void setGroupDesc(String groupDesc)
    {
        this.groupDesc = groupDesc;
    }
    
    public String getStrBuffer()
    {
        return strBuffer;
    }
    
    public void setStrBuffer(String strBuffer)
    {
        this.strBuffer = strBuffer;
    }
    
    public String getOrgCode()
    {
        return orgCode;
    }
    
    public void setOrgCode(String orgCode)
    {
        this.orgCode = orgCode;
    }
    
    public String getUserId()
    {
        return userId;
    }
    
    public void setUserId(String userId)
    {
        this.userId = userId;
    }
    
    public Long getGroupId()
    {
        return groupId;
    }
    
    public void setGroupId(Long groupId)
    {
        this.groupId = groupId;
    }
}